package com.hnu.store.config;

import com.alibaba.fastjson.JSONObject;
import com.hnu.store.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 拦截器
 */

@Component
public class TokenInterceptor implements HandlerInterceptor {

  /**
   * 预处理http请求
   * @param request current HTTP request
   * @param response current HTTP response
   * @param handler chosen handler to execute, for type and/or instance evaluation
   * @return 返回预处理结果
   * @throws Exception 抛出异常
   */

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    //  预检请求为OPTIONS请求，用于向服务器请求权限信息
    if (request.getMethod().equals("OPTIONS")) {
      response.setStatus(HttpServletResponse.SC_OK);
      return true;
    }
    response.setCharacterEncoding("utf-8");
    //  前端vue将token添加在请求头中
    String token = request.getHeader("token");
    System.out.println("token:"+token);

    JSONObject json = new JSONObject();
    json.put("message", "token失效");
    json.put("code", "4006");
    if (token != null) {
      try {
        Claims claims = JwtUtils.getClaimsByToken(token);
        System.out.println(claims.getExpiration().getTime());
        //  token失效了
        if (claims.getExpiration().getTime() < new Date().getTime()) {
          response.getWriter().append(json.toJSONString());
          System.out.println("超时");
          return false;
        } else {
          //  没有失效
          return true;
        }
      } catch (Exception e) {
        response.getWriter().append(json.toJSONString());
        return false;
      }
    }

    try {
      //  json写入response
      response.getWriter().append(json.toJSONString());
    } catch (Exception e) {
      e.printStackTrace();
      response.sendError(500);
      return false;
    }
    return false;
  }
}
